import numpy as np
import cv2
import uuid
from PIL import Image
import os

def mask_data():
    if (os.path.exists("mask.npy")):
        data = np.load("mask.npy",allow_pickle=True)
        return data.tolist()
    else:
        data = []
        return data

def get_name():
    uuid_str = uuid.uuid4().hex
    file_name = uuid_str + ".png"
    return file_name

def photo():
    cap = cv2.VideoCapture(1)
    # 从摄像头获取图像，第一个为布尔变量表示成功与否，第二个变量是图像
    ret, filename = cap.read()
    # 保存图像至Haar相同路径
    img_name = get_name()
    cv2.imwrite('./Pic/' + img_name, filename)
    # 释放摄像头资源
    cap.release()
    imagefile = "./Pic/" + img_name
    img = Image.open(imagefile)  # 返回一个Image对象
    # os模块中的path目录下的getSize()方法获取文件大小，单位字节Byte
    size = os.path.getsize(imagefile)  # 计算图片大小即KB
    # size的两个参数
    width, height = img.size[0], img.size[1]
    # 用于保存压缩过程中的temp路径,每次压缩会被不断覆盖
    newPath = 'temp.jpg'
    while size > 1024 * 1024 * 5:
        width, height = round(width * 0.9), round(height * 0.9)
        print(width, height)
        img = img.resize((width, height), Image.ANTIALIAS)
        img.save(newPath)
        size = os.path.getsize(newPath)
    # 压缩完成
    img.save(imagefile)
    return "https://pic.cpolar.cn/"+img_name


import json
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.iai.v20200303 import iai_client, models
from PIL import Image

def mask(time,Url):
    answer = []
    cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
    httpProfile = HttpProfile()
    httpProfile.endpoint = "iai.tencentcloudapi.com"
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)
    req = models.DetectFaceRequest()
    params = {
        "MaxFaceNum": 1,
        "Url": Url,
        "NeedFaceAttributes": 1,
        "NeedQualityDetection": 1,
        "NeedRotateDetection": 1
    }
    req.from_json_string(json.dumps(params))
    resp = client.DetectFace(req)
    ans = json.loads(resp.to_json_string())
    answer.append(ans)

    cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
    httpProfile = HttpProfile()
    httpProfile.endpoint = "iai.tencentcloudapi.com"
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)
    req = models.SearchFacesRequest()
    params = {
        "GroupIds": ["DLUT"],
        "Url": Url,
        "MaxFaceNum": 1,
        "MaxPersonNum": 3,
        "NeedPersonInfo": 1,
        "QualityControl": 0,
        "NeedRotateDetection": 1
    }
    req.from_json_string(json.dumps(params))
    resp = client.SearchFaces(req)
    ans = json.loads(resp.to_json_string())
    answer.append(ans)

    data = answer
    ans = mask_data()
    insert = []
    insert.append(time)
    insert.append(Url)
    if data[0]["FaceInfos"][0]["FaceAttributesInfo"]["Mask"]:
        insert.append("佩戴口罩")
    else:
        insert.append("未佩戴口罩")
    if data[0]["FaceInfos"][0]["FaceQualityInfo"]["Completeness"]["Nose"] <= 40 and \
            data[0]["FaceInfos"][0]["FaceQualityInfo"]["Completeness"]["Mouth"] <= 40:
        insert.append("口罩佩戴标准")
    else:
        insert.append("未有效佩戴")
    insert.append(data[1]["Results"][0]["Candidates"][0]["PersonId"])
    insert.append(data[1]["Results"][0]["Candidates"][0]["PersonName"])
    ans.append(insert)
    np.save("mask.npy", np.array(ans))
    return insert